<template>
  <el-drawer
    v-model="show_plan_box"
    direction="rtl"
    size="80%"
    destroy-on-close
    :close-on-click-modal="false"
    @close="close"
  >
    <template #title><h4>进度分配</h4></template>
    <template #default>
      <div class="flex">
        <div>选择设计成员：</div>
        <el-select v-model="searchUserId" @change="change_searchUserId">
          <el-option
            v-for="item in dept_member_list"
            :key="item.memberId"
            :value="item.memberId"
            :label="item.memberName"
          >
          </el-option>
        </el-select>
      </div>
      <el-table
        :data="data"
        border
        :span-method="objectSpanMethod"
        class="m_top10"
        max-height="600"
      >
        <el-table-column label="任务" prop="taskName" fixed></el-table-column>
        <el-table-column
          label="子任务"
          prop="taskNodeConfigName"
          fixed
        ></el-table-column>
        <el-table-column label="总进度(%)">
          <el-table-column
            width="100"
            v-for="(item, index) in days_list"
            :key="item"
            :label="formatDate(Number(item), 'YYYY-MM-DD')"
          >
            <template #default="scope">
              <div
                v-if="scope.row.taskMemberNodePlanList?.length"
                class="m_0_5"
              >
                <el-input
                  v-model="
                    scope.row.taskMemberNodePlanList[index].completionRate
                  "
                  type="number"
                ></el-input>
              </div>
            </template>
          </el-table-column>
        </el-table-column>
      </el-table>
      <div class="m_top10 tr">
        <el-button @click="EventBus.emit('close_box')">取消</el-button>
        <el-button @click="submit" type="primary">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script lang="ts" setup>
import { days, formatDate } from '@/utils/check_role' // 权限校验
import { ref, toRefs } from 'vue'
import axios from '@/service/HttpRequest'
import serviceApi from '@/service/api'
import EventBus from '@/utils/EventBus'
import { ElMessage, ElMessageBox } from 'element-plus'
const props = defineProps({
  show_plan_box: Boolean,
  task_id: String,
  dept_member_list: Array,
})
const { task_id, dept_member_list } = toRefs<any>(props)
const searchUserId = ref('')
const data = ref()
const days_list = ref([])
const current_node_plan_list = ref()
const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  if (columnIndex === 0) {
    if (row.all_nodes) {
      return {
        rowspan: row.all_nodes,
        colspan: 1,
      }
    } else {
      return {
        rowspan: 0,
        colspan: 0,
      }
    }
  }
}
const submit = () => {
  let addList = []
  let deleteIdList = []
  let updateList = []
  console.log(data.value, current_node_plan_list.value)
  let flag = 0
  data.value.forEach((i) => {
    let item_list = i.taskMemberNodePlanList.filter((ii) => {
      return ii.completionRate != ''
    })
    if (item_list.length && item_list.at(-1).completionRate != '100') {
      flag = 1
    }
    let over_100 = i.taskMemberNodePlanList.some((ii) => {
      return ii.completionRate > 100
    })
    if (over_100) flag = 2
    if (flag == 0) {
      i.taskMemberNodePlanList.forEach((ii, index) => {
        // 新增 子任务不同  或 子任务相同 日期 不同
        let is_add_node = current_node_plan_list.value.every((xx) => {
          return (
            xx.taskMemberNodeId != i.id ||
            (xx.taskMemberNodeId == i.id &&
              days_list.value[index] != xx.scheduleDate)
          )
        })
        if (ii.completionRate != '' && is_add_node) {
          let obj = {
            completionRate: ii.completionRate,
            scheduleDate: days_list.value[index],
            taskMemberNodeId: i.id,
          }
          addList.push(obj)
        }
        // 编辑 子任务 日期相同  进度不同 且 不为 空/0
        current_node_plan_list.value.some((xx) => {
          if (
            xx.taskMemberNodeId == i.id &&
            xx.completionRate != ii.completionRate &&
            ii.completionRate != '' &&
            days_list.value[index] == xx.scheduleDate
          ) {
            let obj = {
              completionRate: ii.completionRate,
              taskMemberNodePlanId: xx.id,
            }
            updateList.push(obj)
          }
          return (
            xx.taskMemberNodeId == i.id &&
            xx.completionRate != ii.completionRate &&
            ii.completionRate != '' &&
            days_list.value[index] == xx.scheduleDate
          )
        })
        // 删除 子任务 日期相同  进度为 空/0
        current_node_plan_list.value.some((xx) => {
          if (
            xx.taskMemberNodeId == i.id &&
            days_list.value[index] == xx.scheduleDate &&
            ii.completionRate == ''
          ) {
            deleteIdList.push(xx.id)
          }
          return (
            xx.taskMemberNodeId == i.id &&
            days_list.value[index] == xx.scheduleDate &&
            ii.completionRate == ''
          )
        })
      })
    }
  })
  if (flag == 1) {
    ElMessage.error('已分配的任务子任务的最后总进度需为100')
    return
  }
  if (flag == 2) {
    ElMessage.error('所有任务子任务的总进度均不可超过100')
    return
  }
  let data1 = {
    addList: addList,
    deleteIdList: deleteIdList,
    updateList: updateList,
  }

  console.log(data1)
  ElMessageBox.confirm('确定分配进度？', '', {
    closeOnClickModal: false,
    type: 'warning',
  })
    .then(() => {
      axios
        .request({
          url: serviceApi.taskSetUpPlan + '/' + task_id.value,
          method: 'post',
          data: data1,
        })
        .then((res) => {
          ElMessage.success('操作成功！')
          change_searchUserId()
        })
        .catch((err) => {
          ElMessage.error(err)
        })
    })
    .catch(() => {})
}

const change_searchUserId = () => {
  axios
    .request({
      url: serviceApi.taskSetUpPlan + '/' + task_id.value,
      method: 'get',
      params: { searchUserId: searchUserId.value },
    })
    .then((res) => {
      console.log(res)
      let all_list = []
      res.data.taskMemberList.forEach((i) => {
        if (i.taskMemberNodeList.length) {
          i.taskMemberNodeList[0].all_nodes = i.taskMemberNodeList.length
          i.taskMemberNodeList.forEach((ii) => {
            ii.taskName = i.taskName
            all_list.push(ii)
          })
        }
      })

      let dayss = days(res.data.planEndTime, res.data.planStartTime)
      days_list.value = []
      current_node_plan_list.value = []
      for (let ii = 0; ii <= dayss; ii++) {
        days_list.value.push(
          Number(res.data.planStartTime) + 24 * 60 * 60 * 1000 * ii
        )
      }
      all_list.forEach((i) => {
        days_list.value.forEach((ii, index) => {
          let has_plan = i.taskMemberNodePlanList.some((iii) => {
            if (iii.scheduleDate == ii) {
              iii.taskMemberNodeId = i.id
              current_node_plan_list.value.push(JSON.parse(JSON.stringify(iii)))
            }
            return iii.scheduleDate == ii
          })
          if (!has_plan) {
            i.taskMemberNodePlanList.splice(index, 0, {
              completionRate: '',
              scheduleDate: '',
            })
          }
        })
      })
      data.value = all_list
      console.log(all_list, days_list.value)
    })
    .catch((err) => {
      ElMessage.error(err)
    })
}
const close = () => {
  searchUserId.value = ''
  data.value = []
  days_list.value = []
  EventBus.emit('close_box')
}
</script>

<style lang="scss" scoped></style>
